import React, { useState } from 'react';
import { Typography, Table, Card, Space, Button, Tag, Input, Select, Modal, Form, Alert, Tabs } from 'antd';
import {
  DatabaseOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  CloudOutlined,
  CheckCircleOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Title, Text } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;

interface DNSRecord {
  id: string;
  name: string;
  type: 'A' | 'AAAA' | 'CNAME' | 'MX' | 'TXT' | 'NS';
  value: string;
  ttl: number;
  status: 'active' | 'inactive';
}

interface Domain {
  id: string;
  name: string;
  status: 'active' | 'pending' | 'expired';
  provider: string;
  expiryDate: string;
  autoRenew: boolean;
  records: DNSRecord[];
}

const DomainManage: React.FC = () => {
  const [searchText, setSearchText] = useState('');
  const [modalVisible, setModalVisible] = useState(false);
  const [recordModalVisible, setRecordModalVisible] = useState(false);
  const [selectedDomain, setSelectedDomain] = useState<Domain | null>(null);
  const [form] = Form.useForm();
  const [recordForm] = Form.useForm();

  // 模拟域名数据
  const [domains] = useState<Domain[]>([
    {
      id: '1',
      name: 'example.com',
      status: 'active',
      provider: '阿里云',
      expiryDate: '2024-12-15',
      autoRenew: true,
      records: [
        { id: '1', name: '@', type: 'A', value: '192.168.1.1', ttl: 600, status: 'active' },
        { id: '2', name: 'www', type: 'CNAME', value: 'example.com', ttl: 600, status: 'active' },
        { id: '3', name: 'mail', type: 'MX', value: '10 mail.example.com', ttl: 3600, status: 'active' },
      ]
    },
    {
      id: '2',
      name: 'test.com',
      status: 'pending',
      provider: '腾讯云',
      expiryDate: '2024-06-20',
      autoRenew: false,
      records: [
        { id: '4', name: '@', type: 'A', value: '192.168.1.2', ttl: 600, status: 'active' },
      ]
    },
    {
      id: '3',
      name: 'old-site.com',
      status: 'expired',
      provider: 'Godaddy',
      expiryDate: '2023-12-01',
      autoRenew: false,
      records: []
    }
  ]);

  const getStatusConfig = (status: Domain['status']) => {
    const configs = {
      active: { color: 'success', text: '正常' },
      pending: { color: 'processing', text: '待验证' },
      expired: { color: 'error', text: '已过期' }
    };
    return configs[status];
  };

  const filteredDomains = domains.filter(domain =>
    domain.name.toLowerCase().includes(searchText.toLowerCase())
  );

  const handleAddRecord = (domain: Domain) => {
    setSelectedDomain(domain);
    recordForm.resetFields();
    setRecordModalVisible(true);
  };

  const recordColumns: ColumnsType<DNSRecord> = [
    {
      title: '记录名',
      dataIndex: 'name',
      key: 'name',
      render: (name: string) => (
        <Text strong>{name === '@' ? '主域名' : name}</Text>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => <Tag color="blue">{type}</Tag>,
    },
    {
      title: '记录值',
      dataIndex: 'value',
      key: 'value',
      ellipsis: true,
    },
    {
      title: 'TTL',
      dataIndex: 'ttl',
      key: 'ttl',
      render: (ttl: number) => `${ttl}s`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: DNSRecord['status']) => (
        <Tag color={status === 'active' ? 'success' : 'default'}>
          {status === 'active' ? '生效' : '未生效'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="small">
          <Button type="link" size="small" icon={<EditOutlined />}>
            编辑
          </Button>
          <Button type="link" size="small" danger icon={<DeleteOutlined />}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const domainColumns: ColumnsType<Domain> = [
    {
      title: '域名',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => (
        <Space>
          <DatabaseOutlined style={{ color: '#1890ff' }} />
          <Text strong>{text}</Text>
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: Domain['status']) => {
        const config = getStatusConfig(status);
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '服务商',
      dataIndex: 'provider',
      key: 'provider',
    },
    {
      title: '到期时间',
      dataIndex: 'expiryDate',
      key: 'expiryDate',
      render: (date: string) => {
        const expiryDate = new Date(date);
        const today = new Date();
        const daysLeft = Math.ceil((expiryDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
        
        return (
          <Space direction="vertical" size="small">
            <Text>{date}</Text>
            {daysLeft > 0 ? (
              <Text type={daysLeft < 30 ? 'danger' : 'secondary'} style={{ fontSize: 12 }}>
                {daysLeft}天后到期
              </Text>
            ) : (
              <Text type="danger" style={{ fontSize: 12 }}>
                已过期{Math.abs(daysLeft)}天
              </Text>
            )}
          </Space>
        );
      },
    },
    {
      title: '自动续费',
      dataIndex: 'autoRenew',
      key: 'autoRenew',
      render: (autoRenew: boolean) => (
        <Tag color={autoRenew ? 'blue' : 'default'}>
          {autoRenew ? '已启用' : '已禁用'}
        </Tag>
      ),
    },
    {
      title: '记录数',
      key: 'recordCount',
      render: (_, record) => (
        <Text>{record.records.length}</Text>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small" wrap>
          <Button
            type="link"
            size="small"
            onClick={() => handleAddRecord(record)}
          >
            DNS解析
          </Button>
          <Button type="link" size="small" icon={<EditOutlined />}>
            编辑
          </Button>
          <Button type="link" size="small" danger icon={<DeleteOutlined />}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'flex-start',
        marginBottom: '24px'
      }}>
        <div>
          <Title level={2} style={{ margin: 0, marginBottom: '8px' }}>
            <DatabaseOutlined style={{ marginRight: '8px', color: '#722ed1' }} />
            域名管理
          </Title>
          <Text type="secondary">管理域名解析和DNS配置</Text>
        </div>
        <Button 
          type="primary" 
          size="large"
          icon={<PlusOutlined />}
          onClick={() => setModalVisible(true)}
        >
          添加域名
        </Button>
      </div>

      {/* 域名过期提醒 */}
      {domains.some(d => {
        const expiryDate = new Date(d.expiryDate);
        const today = new Date();
        const daysLeft = Math.ceil((expiryDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
        return daysLeft <= 30 && daysLeft > 0;
      }) && (
        <Alert
          message="域名即将到期"
          description="发现有域名即将在30天内到期，请及时续费以避免服务中断"
          type="warning"
          showIcon
          style={{ marginBottom: '24px' }}
          action={
            <Button size="small">查看详情</Button>
          }
        />
      )}

      {/* 搜索框 */}
      <Card style={{ marginBottom: '16px' }}>
        <Input
          placeholder="搜索域名"
          prefix={<SearchOutlined />}
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          style={{ width: 300, marginBottom: '16px' }}
        />

        <Table
          columns={domainColumns}
          dataSource={filteredDomains}
          rowKey="id"
          expandable={{
            expandedRowRender: (record) => (
              <div style={{ margin: 0 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
                  <Title level={5}>DNS解析记录</Title>
                  <Button 
                    type="primary" 
                    size="small" 
                    icon={<PlusOutlined />}
                    onClick={() => handleAddRecord(record)}
                  >
                    添加记录
                  </Button>
                </div>
                <Table
                  columns={recordColumns}
                  dataSource={record.records}
                  rowKey="id"
                  pagination={false}
                  size="small"
                />
              </div>
            ),
            rowExpandable: (record) => record.records.length > 0,
          }}
          pagination={{
            total: filteredDomains.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
        />
      </Card>

      {/* 添加域名模态框 */}
      <Modal
        title="添加域名"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => {
          form.validateFields().then(() => {
            setModalVisible(false);
            form.resetFields();
          });
        }}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="domain"
            label="域名"
            rules={[
              { required: true, message: '请输入域名' },
              { pattern: /^[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*$/, message: '请输入有效的域名' }
            ]}
          >
            <Input placeholder="example.com" />
          </Form.Item>
          
          <Form.Item
            name="provider"
            label="服务商"
            rules={[{ required: true, message: '请选择服务商' }]}
          >
            <Select placeholder="选择域名服务商">
              <Option value="阿里云">阿里云</Option>
              <Option value="腾讯云">腾讯云</Option>
              <Option value="Godaddy">Godaddy</Option>
              <Option value="Cloudflare">Cloudflare</Option>
              <Option value="其他">其他</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 添加DNS记录模态框 */}
      <Modal
        title={`为 ${selectedDomain?.name} 添加DNS记录`}
        open={recordModalVisible}
        onCancel={() => setRecordModalVisible(false)}
        onOk={() => {
          recordForm.validateFields().then(() => {
            setRecordModalVisible(false);
            recordForm.resetFields();
          });
        }}
      >
        <Form
          form={recordForm}
          layout="vertical"
          initialValues={{
            type: 'A',
            ttl: 600
          }}
        >
          <Form.Item
            name="name"
            label="记录名"
            rules={[{ required: true, message: '请输入记录名' }]}
          >
            <Input placeholder="@ 或 www 或子域名" />
          </Form.Item>
          
          <Form.Item
            name="type"
            label="记录类型"
            rules={[{ required: true, message: '请选择记录类型' }]}
          >
            <Select>
              <Option value="A">A记录</Option>
              <Option value="AAAA">AAAA记录</Option>
              <Option value="CNAME">CNAME记录</Option>
              <Option value="MX">MX记录</Option>
              <Option value="TXT">TXT记录</Option>
              <Option value="NS">NS记录</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="value"
            label="记录值"
            rules={[{ required: true, message: '请输入记录值' }]}
          >
            <Input placeholder="IP地址、域名或其他值" />
          </Form.Item>
          
          <Form.Item
            name="ttl"
            label="TTL"
            rules={[{ required: true, message: '请输入TTL值' }]}
          >
            <Select>
              <Option value={60}>1分钟</Option>
              <Option value={300}>5分钟</Option>
              <Option value={600}>10分钟</Option>
              <Option value={3600}>1小时</Option>
              <Option value={86400}>1天</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DomainManage; 